<template>
  <vue-content>
    <vue-header>
      <vue-header-form>
        <el-form :inline="true" :model="formFilter" ref="formFilter">
          <el-form-item v-if="admShow()" label="企业名称" prop="companyNo">
            <el-select v-model="formFilter.companyNo" @change="selectChange">
              <el-option 
                v-for="item in CompList"
                :key="item.companyNo"
                :label="item.companyName"
                :value="item.companyNo"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="员工姓名" prop="name">
            <el-input v-model.trim="formFilter.name" style="width:100px"></el-input>
          </el-form-item>
          <el-form-item label="员工工号" prop="staffNo">
            <el-input v-model.trim="formFilter.staffNo" style="width:150px"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model.trim="formFilter.phone" style="width:150px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="info" @click="SearchSubmit('formFilter')">查询</el-button>
            <el-button @click="resetForm('formFilter')">重置</el-button>
          </el-form-item>
        </el-form>
      </vue-header-form>
      <vue-header-button>
        <el-button type="info" @click="create">员工新增</el-button>
        <el-button type="info" @click="add">积分添加</el-button>
        <el-button type="info" @click="Import">员工信息导入</el-button>
        <el-button type="info" @click="integralimport">员工积分导入</el-button>
        <el-button type="info" @click="exportForm('staff')">批量导出</el-button>
        <!-- <el-button type="info" @click="exportForm('integral')">积分信息导出</el-button> -->
      </vue-header-button>
    </vue-header>
    <vue-body>
      <el-table
        v-loading.body="loading"
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          prop="name"
          width="150"
          label="员工姓名">
        </el-table-column>
        <el-table-column
          prop="staffNo"
          label="工号">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="电话" width="130">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="idNo"
          label="证件编号">
        </el-table-column>
        <el-table-column
          label="职位">
          <template slot-scope="scope">
            {{scope.row.staffLevel | staffLevel}}
          </template>
        </el-table-column>
        <el-table-column
          prop="usableIntegral"
          label="可用积分">
        </el-table-column>
        <el-table-column label="操作" width="260">
          <template slot-scope="scope">
            <el-button-group>
            <el-button
              :disabled="scope.row.status === '01'?true:false"
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="info"
              @click="handleDetail(scope.$index, scope.row, tableData)">详情</el-button>
            <el-button
              size="mini"
              @click="resetPwd(scope.$index, scope.row)" >重置密码</el-button>
              </el-button-group>
          </template>
      </el-table-column>
      </el-table>
    </vue-body>
    <vue-footer style="padding: 5px 0;margin: 0 -5px;float:right;">
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="10"
        layout="total, prev, pager, next"
        :total="pageSize">
      </el-pagination>
    </vue-footer>
    <import-staff
      ref="import-staff"
      @close="editFinish"
      :view="view"
      v-if="view ==='import' || view ==='integralimport'"/>
    <edit-staff
      ref="edit-staff"
      @close="editFinish"
      :view="view"
      v-if="view ==='create' || view ==='edit'"/>
    <reset-user-pwd
      ref="reset-pwd"
      :view="view"
      @close="editFinish"
      v-if="view==='reset'"/>
    <edit-detail
      ref="edit-detail"
      @close="editFinish"
      :view="view"
      v-if="view ==='detail'"/>
    <integral-add
      ref="integral-add"
      @close="editFinish"
      :view="view"
      v-if="view ==='add'"/>
  </vue-content>
</template>

<script>
  import { md5 } from '@/utilities/crypto' // 加密
  import AuthStorage from '@/services/storage.js'
  import {query,queryCompanyList} from '@/services/staffManager'
  import {RequestError} from '@/services/errors'
  import {deepClone} from '@/utilities/object'
  import {mapGetters} from 'vuex'
  import ImportStaff from './dialog/import'
  import EditStaff from './dialog/edit'
  import EditDetail from './dialog/Detail'
  import IntegralAdd from './dialog/integralAdd'
  import resetUserPwd from './dialog/reset-pwd'
  export default {
    name: 'comp-table',
    components: {EditStaff,EditDetail,ImportStaff,resetUserPwd,IntegralAdd},
    data: () => ({
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      formFilter: {
        name:"",
        staffNo:"",
        phone:"",
        companyNo: "",
      },
      CompList:[],
      loading: false,
      view: ''
    }),
    computed: {
      ...mapGetters(['token'])
    },
    created () {
      // console.log(this.token.userType)
      this.loadCompList();
    },
    methods: {
      admShow(){
        if(this.token.userType == '01'){
          return true
        }else{
          return false
        }
      },
      async loadCompList () {
        try {
          let data = await queryCompanyList();
          this.formFilter.companyNo = data.data[0].companyNo;
          // console.log(data)
          this.CompList = data.data;
          this.loadData();
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
        this.loading = false
      },
      async loadData () {
        this.loading = true
        try {
          let data = await query(Object.assign({currentPage: this.currentPage},{perPage:10}, this.formFilter))
          // debugger
          this.tableData = data.data
					this.pageSize = parseInt(data.totalResult)
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
        this.loading = false
      },
      Import () {
        // this.view = 'import';
        this.$router.push({
	        path: 'staffManager/Importinfo', 
	        name: 'Importinfo',
	        query: { 
            companyNo: this.formFilter.companyNo
          }
        })
      },
      integralimport () {
        this.$router.push({
	        path: 'staffManager/integralimport',
	        name: 'integralimport',
	        query: { 
            companyNo: this.formFilter.companyNo
          }
        })
      },
      async create () {
        this.view = 'create'
        await this.$nextTick()
        this.$refs['edit-staff'].formData.companyNo = this.formFilter.companyNo;
      },
      async add () {
        this.view = 'add'
        await this.$nextTick()
        this.$refs['integral-add'].formData.companyNo = this.formFilter.companyNo;
      },
      async handleEdit (index, data) {
        this.view = 'edit'
        await this.$nextTick()
        this.$refs['edit-staff'].dialogFormVisible = true
        this.$refs['edit-staff'].formFilter = deepClone(data)
        this.$refs['edit-staff'].loadData();
      },
      async resetPwd (index, data) {
        this.view = 'reset'
        await this.$nextTick()
        this.$refs['reset-pwd'].formData.name = data.name
        this.$refs['reset-pwd'].formData.serialNo = data.serialNo
      },
      async handleDetail (index, data) {
        this.view = 'detail'
        await this.$nextTick()
        this.$refs['edit-detail'].tableData = deepClone(data)
      },
      async exportForm (type) {
        var param=Object.assign({currentPage: this.currentPage},{perPage:10},this.formFilter);
        var  a = new Date();
        var btime= a .getTime();
        var signs2 = "data="+JSON.stringify(param)+"&stmb="+btime;
        if(type == 'staff'){
          this.postDownLoadFile({
            url: this.$store.state.exportUrl + 'ecshop/staff/companyStaffInfoExport.do?stmb='+ a.getTime() +'&source="03"&token='+ AuthStorage.token +'&version=""&data='+JSON.stringify(param)+'&sign='+this.signature(signs2),
            method:'post'
          });
        }else{
          this.postDownLoadFile({
            url: this.$store.state.exportUrl + 'ecshop/staff/companyStaffInfoExport.do?stmb='+ a.getTime() +'&source="03"&token='+ AuthStorage.token +'&version=""&data='+JSON.stringify(param)+'&sign='+this.signature(signs2),
            method:'post'
          });
        }
      },
      signature(data) {
        return md5(data)
      },
      postDownLoadFile(options) {
        var config = $.extend(true, { method: 'post' }, options);
        var $iframe = $('<iframe id="down-file-iframe" />');
        var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
        $form.attr('action', config.url);
        for (var key in config.data) {
            $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
        }
        $iframe.append($form);
        $(document.body).append($iframe);
        $form[0].submit();
        $iframe.remove();
      },
      selectChange(item){
        // console.log(item)
        this.formFilter.companyNo = item;
        this.loadData()
      },
      SearchSubmit () {
        this.currentPage = 1
        this.loadData()
      },
      resetForm (formName) {
        // this.$refs[formName].resetFields()
        this.formFilter.name = "";
        this.formFilter.staffNo = "";
        this.formFilter.phone = "";
        this.currentPage = 1
        this.loadData()
      },
      editFinish (needRefresh) {
        this.view = ''
        if(needRefresh){
          this.$nextTick(() => {
            // dom元素更新后执行， 因此此处能正确打印出更改之后的值；
            this.loadData()
         	})
        }
      }
    },
    watch: {
      currentPage (newVal) {
        this.loadData(newVal)
      }
    },
    filters: {
      staffLevel (value) {
        return {"01": '普通员工'}[value]
      }
    }
  }
</script>

<style>
	.logoImgPic{
		height: 100px;
		display: block;
	}
	.el-table th>.cell{
		text-align: center;
	}
</style>
